package com.gxa.customer.controller;


import com.gxa.common.commons.JsonResult;
import com.gxa.common.commons.R;
import com.gxa.common.pojo.AppUser;

import com.gxa.common.pojo.Country;
import com.gxa.common.pojo.Emailpojo;
import com.gxa.common.utils.AliSendSmsUtil;
import com.gxa.common.utils.EmailUtils;
import com.gxa.common.utils.FileUtils;
import com.gxa.common.utils.RandomUtils;
import com.gxa.customer.service.AppUserService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/customer/appUser")
public class AppUserController {

    @Autowired
    private AppUserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 分页展示所有用户信息列表
     * @param pageNo 当前页
     * @param pageSize 每页显示数量
     * @return
     */
    @GetMapping(value = "/selectAllUser")
    public JsonResult selectAllUser(Integer pageNo,Integer pageSize){
        JsonResult jsonResult=userService.selectUserByPage(pageNo,pageSize);
        return jsonResult;
    }


    /**
     * 用手机号登陆
     */
    @GetMapping(value = "/loginByPhone")
    public R  loginByPhone(String phone){
        AppUser appUser=userService.selectUserByPhone(phone);
        R r =new R();
        if(appUser!=null){
            r.setCode(200);
            r.setMsg("登陆成功!");
        }else{
            r.setCode(500);
            r.setMsg("电话号码错误!");
        }
        return r;
    }



    /**
     * 通过微信登陆
     */
    @GetMapping(value = "/loginByWeixin")
    public R  loginByWeixin(String userNickName){
        AppUser appUser=userService.selectUserByUserNickName(userNickName);
        R r =new R();
        if(appUser!=null){
            r.setCode(200);
            r.setMsg("登陆成功!");
        }else{
            r.setCode(500);
            r.setMsg("微信登陆失败!");
        }
        return r;
    }
    /**
     * 绑定账号
     * @param phone 电话号码
     * @return
     */
    @PostMapping(value = "/register")
    public R register(String phone){
        userService.insertAppUser(phone);
        R r=new R();
        r.setCode(200);
        r.setMsg("注册成功");
        return r;
    }



    /**
     * 通过电话号码分页展示所有用户信息列表
     * @param pageNo 当前页
     * @param pageSize 每页显示数量
     * @return
     */
    @GetMapping(value = "/selectAllUserByItems")
    public JsonResult selectAllUserByItems(Integer pageNo,Integer pageSize,String phone,String userNickName){
        JsonResult jsonResult=userService.selectUsersByItems(pageNo,pageSize,phone,userNickName);
        return jsonResult;
    }


    /**
     * 冻结账户的方法
     */
    @PostMapping(value = "/frozenAccount")
    public R frozenAccount(Long id){
        userService.updateStatus(id);
        R r=new R();
        r.setCode(200);
        r.setMsg("冻结账户成功");
        return r;
    }

    /**
     * 查询某一个用户信息的方法
     */
    @GetMapping(value = "/showUser")
    public R showUser(Long id){
        AppUser appUser=userService.selectUserById(id);
        R r =new R();
        if(appUser!=null){
            r.setCode(200);
            r.setMsg("查询成功!");
            r.setData(appUser);
        }else{
            r.setCode(500);
            r.setMsg("查询失败!");
        }
        return r;
    }


    /**
     * 查询区所有国家的方法
     * @return
     */
    @GetMapping(value = "/selectAllCountry")
    public R selectAllCountry(){
        List<Country> countries=userService.selectAllCountry();
        R r=new R();
        r.setCode(200);
        r.setData(countries);
        return r;
    }


    /**
     * 通过用户id更改用户信息的方法
     */
    @PostMapping(value = "/updateUser")
    public R updateUser(MultipartFile file, AppUser appUser, HttpServletRequest request){
        String url= FileUtils.fileUpload("/appUser",file,request);
        appUser.setAppUserIcon(url);
        userService.updateUser(appUser);
        R r=new R();
        r.setCode(200);
        r.setMsg("账户更改成功");
        return r;
    }
    //查看用户收藏的商海信息
    @RequestMapping("/findUserCollectionMerchant")
    public R findUserCollectionMerchant(Long appUserId){
        return userService.findUserCollectionMerchant(appUserId);
    }

    //获取手机验证码
    @RequestMapping("/receiveCodeByPhone")
    public R receiveCodeByPhone(String phone){
        R r=new R();
        //统计验证码发送次数
        String countKey="VerifyPhone" + phone +":count";
        //每个手机号一天只能发送三次
        Object count = redisTemplate.opsForValue().get(countKey);
        if (count==null){
            redisTemplate.opsForValue().set(countKey,"1",60*60*24, TimeUnit.SECONDS);
        }else if (Integer.parseInt(count.toString()) <=2){
            redisTemplate.opsForValue().increment(countKey);
        }else if(Integer.parseInt(count.toString())>2){
            r.setCode(500);
            r.setMsg("此号码今天已发送3次验证码！");
            return r;
        }
        //发送验证码
        String codeKey="VerifyCode"+phone+":code";
        //随机生成6位数验证码
        String VerCode = RandomUtils.generateNumberString(6);
        //验证码存到redis中，有效期为3分钟
        redisTemplate.opsForValue().set(codeKey,VerCode,60*5,TimeUnit.SECONDS);
        //调用工具类发送验证码
        boolean sendSms = AliSendSmsUtil.sendSms(phone, VerCode);
        if (sendSms){
            r.setCode(200);
            r.setMsg("成功发送验证码到"+ phone);
        }else {
            r.setCode(500);
            r.setMsg("发送验证码失败！");
        }
        return r;
    }
    //手机验证码登录+注册邮箱提醒
    @PostMapping("/loginByVerCode")
    public R loginByVerCode(String phone, String verCode,String email, HttpServletResponse response){
        R r=new R();
        System.out.println(phone);
        System.out.println(verCode);
        System.out.println(email);
        if(email==null){
            r.setCode(500);
            r.setMsg("邮箱不能为空！");
            return r;
        }
        if(phone==null){
            r.setCode(500);
            r.setMsg("电话不能为空！");
            return r;
        }
        if(verCode==null){
            r.setCode(500);
            r.setMsg("验证码不能为空！");
            return r;
        }
        AppUser appUser=userService.selectUserByPhone(phone);
        if (appUser==null){
            //无该手机号相关用户，进行注册
            userService.registerByPhone(phone);
            //注册成功，异步发送邮箱
            Emailpojo emailpojo = new Emailpojo(email, "欧森系统注册", "你的手机号" + phone + "已成功注册到欧森系统！");
            rabbitTemplate.convertAndSend("X", "XA",  emailpojo);

//            EmailUtils.sendMail(email, "欧森系统注册", "你的手机号" + phone + "已成功注册到欧森系统！");
        }
        String codeKey="VerifyCode"+phone+":code";
        //获取redis中的验证码
        Object redisCode = redisTemplate.opsForValue().get(codeKey);
        //判断用户输入的验证码是否等于redis中缓存的验证码
        if(redisCode==null){
            r.setCode(500);
            r.setMsg("验证码已过期，请重新发送！");
        }else if(redisCode.toString().equals(verCode)){
            //生成token
            String token = RandomUtils.generateString(100);
            //通过手机号查询出该用户的信息返回给前端
            Map<String, Object> userInfoByPhoneMap = userService.findUserInfoByPhone(phone);
//            System.out.println(userInfoByPhoneMap);
            if (userInfoByPhoneMap==null){
                r.setCode(500);
                r.setMsg("没找到数据");
                r.setData(userInfoByPhoneMap);
                return r;
            }
            userInfoByPhoneMap.put("token",token);
            //将token存入redis，有效时间30分钟
            redisTemplate.opsForValue().set("token",token,60*30,TimeUnit.SECONDS);
            //通过响应头返回给前端
            response.setHeader("token",token);
            //暴露到响应头
            response.setHeader("Access-Control-Expose-Headers","token");
            r.setCode(200);
            r.setMsg("登录成功！");
            r.setData(userInfoByPhoneMap);
        }else {
            r.setCode(500);
            r.setMsg("输入的验证码有误！");
        }
        return r;
    }


}
